Skip to main content

C# : Interview questions (31-35)


  Questions :

      • How do you handle null reference exceptions in C#?
      • Explain the concept of delegates in C#.
      • What is a multicast delegate?
      • What is an event in C#?
      • Explain the difference between events and delegates.

      Answers :

      Handling Null Reference Exceptions in C#:

      Null Reference Exceptions occur when you try to access a member or method of an object that is null. To handle these exceptions, you can use conditional statements to check for null values before accessing members or methods, or you can use the null-conditional operator (?.) introduced in C# 6.0.

      // Using conditional statements
      if (obj != null) 
      {
          obj.Method();
      }
      
      // Using null-conditional operator
      obj?.Method();
      

      In both cases, the method Method() is only called if obj is not null, preventing a Null Reference Exception.

      Delegates in C#:

      Delegates in C# are reference types that hold references to methods, allowing methods to be passed as arguments to other methods or stored as data. They enable a form of function pointer or callback mechanism, facilitating encapsulation and loose coupling in applications.

      delegate void MyDelegate(string message);
      
      class Program 
      {
          static void Main() 
          {
              MyDelegate delegateObj = new MyDelegate(PrintMessage);
              delegateObj("Hello, World!");
          }
      
          static void PrintMessage(string message) 
          {
              Console.WriteLine(message);
          }
      }
      

      In this example, MyDelegate is a delegate type that can hold references to methods with a signature matching void methodName(string). The delegate is instantiated with the PrintMessage method and invoked with a message string.

      Multicast Delegate:

      A multicast delegate in C# is a delegate that holds references to multiple methods. When invoked, a multicast delegate invokes all the methods it holds in the order they were added. Multicast delegates are commonly used in event handling scenarios.

      delegate void MyDelegate();
      
      class Program 
      {
          static void Main() 
          {
              MyDelegate delegateObj = Method1;
              delegateObj += Method2;
              delegateObj();
          }
      
          static void Method1() 
          {
              Console.WriteLine("Method 1");
          }
      
          static void Method2() 
          {
              Console.WriteLine("Method 2");
          }
      }
      

      In this example, delegateObj is a multicast delegate that holds references to both Method1 and Method2. When invoked, it calls both methods sequentially.

      Event in C#:

      An event in C# is a language construct that allows a class to provide notifications to other classes when certain actions occur. Events are based on delegates and follow the publisher-subscriber pattern, where one class (the publisher) raises events and other classes (subscribers) handle them.

      class Button 
      {
          public event EventHandler Click;
      
          public void OnClick() 
          {
              Click?.Invoke(this, EventArgs.Empty);
          }
      }
      

      In this example, the Click event is declared in the Button class. Subscribers can attach event handlers to the Click event and be notified when the button is clicked by calling the OnClick method.

      Difference between Events and Delegates:

      • Delegates: Delegates are types that hold references to methods. They enable method invocation through delegate instances.
      • Events: Events are a higher-level language construct built on top of delegates. They provide a standardized way for classes to provide notifications of state changes or actions to other classes without exposing their internal implementation.

      In summary, delegates are the building blocks for events, while events provide a more structured and encapsulated way to implement the observer pattern in C#.

      C# : Interview questions (36-40)

      Comments

      Popular posts from this blog

      Optional Parameters in C# — Writing Flexible and Clean Methods

      Hello, .NET developers! 👋 How often have you created multiple method overloads just to handle slightly different cases? Maybe one method accepts two parameters, another three, and one more adds a flag for debugging? That’s a lot of code duplication for something that can be solved beautifully with optional parameters . Optional parameters in C# let you define default values for method arguments. When a caller doesn’t pass a value, the compiler automatically substitutes the default. This feature helps keep your APIs simple, readable, and maintainable. 🎥 Explore more on YouTube : DotNet Full Stack Dev Understanding Optional Parameters Optional parameters are defined by assigning default values in the method signature. When calling the method, you can omit those parameters if you’re okay with the defaults. Example public class Logger { public void Log(string message, string level = "INFO", bool writeToFile = false) ...

      .NET 10: Your Ultimate Guide to the Coolest New Features (with Real-World Goodies!)

       Hey .NET warriors! 🤓 Are you ready to explore the latest and greatest features that .NET 10 and C# 14 bring to the table? Whether you're a seasoned developer or just starting out, this guide will show you how .NET 10 makes your apps faster, safer, and more productive — with real-world examples to boot! So grab your coffee ☕️ and let’s dive into the awesome . 💪 1️⃣ JIT Compiler Superpowers — Lightning-Fast Apps .NET 10 is all about speed . The Just-In-Time (JIT) compiler has been turbocharged with: Stack Allocation for Small Arrays 🗂️ Think fewer heap allocations, less garbage collection, and blazing-fast performance . Better Code Layout 🔥 Hot code paths are now smarter, meaning faster method calls and fewer CPU cache misses. 💡 Why you care: Your APIs, desktop apps, and services now respond quicker — giving users a snappy experience . 2️⃣ Say Hello to C# 14 — More Power in Your Syntax .NET 10 ships with C# 14 , and it’s packed with developer goodies: Field-Bac...

      Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

      RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...